package com.bill.robot.koalacam;

import java.net.URLEncoder;

import org.apache.http.client.CookieStore;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONObject;

/**
 * 年龄性别分析
 * @author litong
 * 2016年7月4日
 */
public class Statistics {

  /**
  * 年龄性别统计
  * @param cookieStore cookie值
  * @param url
  * @param start_time 查询时间段的开始时间
  * @param end_time 查询时间段的结束时间
  */
  public static void overview(CookieStore cookieStore, String url, String start_time, String end_time)
      throws Exception {
    System.out.println("Start GET /statistics/overview 年龄性别统计 ...");

    // 自定义HttpClient 设置CookieStore
    CloseableHttpClient httpclient = HttpClients.custom().setDefaultCookieStore(cookieStore).build();
    HttpGet request = new HttpGet(url + "?start_time=" + URLEncoder.encode(start_time, "UTF-8") + "&end_time="
        + URLEncoder.encode(end_time, "UTF-8"));

    CloseableHttpResponse response = httpclient.execute(request);
    String responseBody = EntityUtils.toString(response.getEntity(), "UTF-8");

    // 解析JSON数据
    JSONObject resp = new JSONObject(responseBody);
    int result = resp.optInt("code", -1);
    if (result != 0) {
      System.err.println("code:" + result + ",desc:" + resp.getString("desc"));
    } else {
      JSONArray array = resp.getJSONObject("data").getJSONArray("ages");
      for (int i = 0; i < array.length(); i++) {
        System.out.println(array.get(i));
      }
    }
  }

  /**    
   * 年龄性别记录
   * @param cookieStore cookie值
   * @param url
   * @param start_time 查询时间段的开始时间
   * @param end_time 查询时间段的结束时间
   */
  public static void event(CookieStore cookieStore, String url, String start_time, String end_time) throws Exception {
    System.out.println("Start GET /statistics/event 年龄性别记录 ...");

    // 自定义HttpClient 设置CookieStore
    CloseableHttpClient httpclient = HttpClients.custom().setDefaultCookieStore(cookieStore).build();
    HttpGet request = new HttpGet(url + "?start_time=" + URLEncoder.encode(start_time, "UTF-8") + "&end_time="
        + URLEncoder.encode(end_time, "UTF-8"));

    CloseableHttpResponse response = httpclient.execute(request);
    String responseBody = EntityUtils.toString(response.getEntity(), "UTF-8");

    // 解析JSON数据
    JSONObject resp = new JSONObject(responseBody);
    int result = resp.optInt("code", -1);
    if (result != 0) {
      System.err.println("code:" + result + ",desc:" + resp.getString("desc"));
    } else {
      JSONArray array = resp.getJSONArray("data");
      for (int i = 0; i < array.length(); i++) {
        JSONObject info = (JSONObject) array.get(i);
        System.out.println("age:" + info.getDouble("age") + ",gender:" + info.getDouble("gender"));
      }
    }
  }
}